package com.hm.oauth.web;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hm.common.common.CommonUtil;
import com.hm.common.model.ControllerResult;
import com.hm.common.model.PageInfo;
import com.hm.common.util.CommonDef.OperationStatus;
import com.hm.oauth.service.UserService;
import com.hm.oauth.vo.UserVo;

/**
 * @author shishun.wang
 * @date 上午11:28:09 2016年8月30日
 * @version 1.0
 * @describe
 */
@Controller
@RequestMapping("user")
public class UserController {

	private static final Logger logger = LoggerFactory.getLogger(UserController.class);

	@Autowired
	private UserService userService;

	@RequestMapping("index")
	public String index() {
		return "user/index";
	}

	@RequestMapping("add")
	public String add() {
		return "user/add";
	}

	@RequestMapping(value = "saveAdd", method = RequestMethod.POST)
	public @ResponseBody ResponseEntity<ControllerResult<String>> add(@RequestBody(required = true) UserVo userVo) {
		try {
			if (CommonUtil.isEmpty(userVo.getName(), userVo.getPhone())) {
				logger.debug("user info is incomplete , phone\name is must param");
				return ControllerResult.failed("user info is incomplete , phone\name is must param");
			}
			return ControllerResult.success(userService.add(userVo), OperationStatus.ADD_SUCCESSFUL);
		} catch (Exception e) {
			return ControllerResult.failed(e);
		}
	}
	
	@RequestMapping(value = "{delId}", method = RequestMethod.DELETE)
	public @ResponseBody ResponseEntity<ControllerResult<String>> delete(@PathVariable("delId") String delId){
		try {
			if (CommonUtil.isEmpty(delId)) {
				logger.debug("request param error like this user/{delId}");
				return ControllerResult.failed("request param error like this user/{delId}");
			}
			return ControllerResult.success(userService.delete(delId), OperationStatus.DELELETE_SUCCESSFUL);
		} catch (Exception e) {
			return ControllerResult.failed(e);
		}
	}

	@RequestMapping("query/{pageNo}/{pageSize}")
	public @ResponseBody ResponseEntity<ControllerResult<PageInfo<UserVo>>> query(@PathVariable("pageNo") int pageNo,
			@PathVariable("pageSize") int pageSize) {
		try {
			if (CommonUtil.isEmpty(pageNo, pageSize)) {
				logger.debug("request param error like this user/query/{pageNo}/{pageSize}");
				return ControllerResult.failed("request param error like this user/query/{pageNo}/{pageSize}");
			}
			return ControllerResult.success(userService.query(pageNo, pageSize), OperationStatus.QUERY_SUCCESSFUL);
		} catch (Exception e) {
			return ControllerResult.failed(e);
		}
	}
}
